package cn.jstars.datatocloud.modules.monitor.task;

import cn.jstars.datatocloud.common.cache.Cache;
import cn.jstars.datatocloud.common.consts.Consts;
import cn.jstars.datatocloud.common.utils.DataUtil;
import cn.jstars.datatocloud.common.utils.PageUtil;
import cn.jstars.datatocloud.modules.base.MqService;
import cn.jstars.datatocloud.modules.monitor.entity.Toimachinestatus;
import cn.jstars.datatocloud.modules.monitor.service.MonitorService;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * Created by Elvish on 2018/9/5 11:06.
 * oschina(https://my.oschina.net/xiaozhutefannao)
 */
public class ParamSetTask implements Runnable{

    private static final Logger LOGGER = LoggerFactory.getLogger(ParamSetTask.class);

    private MqService mqService;
    private MonitorService monitorService;
    private String year;

    public ParamSetTask(MqService mqService, MonitorService monitorService,int year) {
        this.mqService = mqService;
        this.monitorService = monitorService;
        this.year = year + "";
    }

    @Override
    public void run() {

        try {

            // 查询机台参数数据
            List<Toimachinestatus> dataList = monitorService.findParamSet(year);

            // 没有就退出
            if (Lang.isEmpty(dataList)) {
                return;
            }

            // 切分数据
            List<List<Toimachinestatus>> pageList = PageUtil.paging(dataList, 500);

            for (List<Toimachinestatus> list : pageList) {

                // 组装数据
                Map<String, Object> dataMap = Maps.newHashMap();
                dataMap.put("type", "Toimachinestatus");
                dataMap.put("data", JSON.toJSONString(list));

                // 封装发送数据格式
                String sendMsg = DataUtil.getMessage(Consts.DataType.PARAM_SET_DATA, Consts.DBConst.COUNTON_PREFIX + year, Consts.DBConst.TOIMACHINESTATUS_PARAMSET,
                    Cache.factoryId, dataMap);

                try{
                    // 发送云端
                    mqService.convertAndSend(Cache.cloudMQQueueName, sendMsg);
                }catch(Exception e){
                    LOGGER.error("发送机台参数数据异常，睡30秒", e);
                    Thread.sleep(30000);
                    continue;
                }

                // 更新上传状态
                monitorService.updateParamSetUploadStatus(list,year);

            }


        }catch (Exception e){
            LOGGER.error("机台参数数据级联失败",e);
        }

    }
}
